package com.alog.javaee.day38;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Auther: Ye Zhengdong
 * @Date: 2019/2/17 22:19
 * @Description:
 */
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("filename");
        String path = req.getServletContext().getRealPath("/images/" + filename);
        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
        FileInputStream fin = new FileInputStream(path);
        OutputStream out = resp.getOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = fin.read(buf)) != -1){
            out.write(buf, 0, len);
        }
        fin.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
